/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 26/11/2010, 16:05:47
 */

package presentacion.acceso;

import hibernate.objeto.Usuario;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.swing.JOptionPane;
import logica.CapaLogica;
import logica.UsuarioLogica;
import logica.validacion.PacienteValidacion;
import presentacion.CapaPresentacion;
import presentacion.MenuPrincipal;
import presentacion.utilidad.BarMenu;
import presentacion.utilidad.maquetado.Fuente;
import presentacion.utilidad.maquetado.Icono;
import presentacion.utilidad.MensajePresentacion;
import presentacion.utilidad.EMail;

/**
 *
 * @author Rafael
 */
public class Login extends javax.swing.JDialog {

    /** Creates new form Login */
    public Login(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        setearEventosQueCapturanTeclaEnterYEscape();
        personalizarJDialog();
    }

    private void personalizarJDialog() {
        //Barra de menu
        setJMenuBar(BarMenu.createMenuBarLogin(this));

        if (MenuPrincipal.usuarioActivo != null) {
            botonSalir.setText("Cancelar");
            botonSalir.setToolTipText("Cancela la operación");
            botonSalir.setMnemonic('c');
        }
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        textoDescriptivoVentana = new javax.swing.JLabel();
        botonAceptar = new javax.swing.JButton();
        botonSalir = new javax.swing.JButton();
        panelLogin = new javax.swing.JPanel();
        textoClave = new javax.swing.JLabel();
        usuario = new javax.swing.JTextField();
        textoUsuario = new javax.swing.JLabel();
        clave = new javax.swing.JPasswordField();
        textoDescriptivoVentana1 = new javax.swing.JLabel();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ingreso");
        setMinimumSize(new java.awt.Dimension(361, 197));
        setResizable(false);

        textoDescriptivoVentana.setFont(Fuente.FUENTE_TITULO_2);
        textoDescriptivoVentana.setForeground(Fuente.COLOR_NORMAL);
        textoDescriptivoVentana.setText("Ingrese el nombre de usuario y clave");
        textoDescriptivoVentana.setPreferredSize(new java.awt.Dimension(325, 20));

        botonAceptar.setFont(Fuente.FUENTE_BOTON_EXTERNO);
        botonAceptar.setForeground(Fuente.COLOR_NORMAL);
        botonAceptar.setIcon(Icono.ICONO_16_ACEPTAR);
        botonAceptar.setMnemonic('l');
        botonAceptar.setText("Login");
        botonAceptar.setToolTipText("Ingresar al Sistema");
        botonAceptar.setPreferredSize(new java.awt.Dimension(110, 23));
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        botonSalir.setFont(Fuente.FUENTE_BOTON_EXTERNO);
        botonSalir.setForeground(Fuente.COLOR_NORMAL);
        botonSalir.setIcon(Icono.ICONO_16_CANCELAR);
        botonSalir.setText("Salir");
        botonSalir.setToolTipText("Salir del Sistema");
        botonSalir.setPreferredSize(new java.awt.Dimension(110, 23));
        botonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSalirActionPerformed(evt);
            }
        });

        textoClave.setFont(Fuente.FUENTE_LABEL);
        textoClave.setForeground(Fuente.COLOR_NORMAL);
        textoClave.setText("Clave");
        textoClave.setPreferredSize(new java.awt.Dimension(56, 20));

        usuario.setFont(Fuente.FUENTE_TEXTFIELD);
        usuario.setForeground(Fuente.COLOR_NORMAL);
        usuario.setPreferredSize(new java.awt.Dimension(200, 20));

        textoUsuario.setFont(Fuente.FUENTE_LABEL);
        textoUsuario.setForeground(Fuente.COLOR_NORMAL);
        textoUsuario.setText("Usuario");
        textoUsuario.setPreferredSize(new java.awt.Dimension(56, 20));

        clave.setFont(Fuente.FUENTE_TEXTFIELD);
        clave.setForeground(Fuente.COLOR_NORMAL);

        textoDescriptivoVentana1.setFont(Fuente.FUENTE_HIPERVINCULO);
        textoDescriptivoVentana1.setForeground(Fuente.COLOR_HIPERVINCULO);
        textoDescriptivoVentana1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        textoDescriptivoVentana1.setText("<html><u>Olvidé mi usuario y/o clave</u>");
        textoDescriptivoVentana1.setPreferredSize(new java.awt.Dimension(325, 14));
        textoDescriptivoVentana1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                textoDescriptivoVentana1MouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                textoDescriptivoVentana1MouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                textoDescriptivoVentana1MouseExited(evt);
            }
        });

        javax.swing.GroupLayout panelLoginLayout = new javax.swing.GroupLayout(panelLogin);
        panelLogin.setLayout(panelLoginLayout);
        panelLoginLayout.setHorizontalGroup(
            panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textoDescriptivoVentana1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(panelLoginLayout.createSequentialGroup()
                        .addGroup(panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(textoUsuario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textoClave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(clave, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                            .addComponent(usuario, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))))
                .addContainerGap())
        );
        panelLoginLayout.setVerticalGroup(
            panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(panelLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textoClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(textoDescriptivoVentana1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panelLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textoDescriptivoVentana, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textoDescriptivoVentana, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        autenticarLogin();
}//GEN-LAST:event_botonAceptarActionPerformed

    /**
     * Autentica los datos ingresados contra la base de datos.
     *
     */
    private void autenticarLogin() {
        Usuario usuarioBD = UsuarioLogica.getUsuarioPorNombreDeUsuarioYEnBd(
                usuario.getText());

        //Si el usuario es nulo es porque no existe en la bd
        if (usuarioBD != null) {
            //Se verifica la clave
            if (usuarioBD.getClaveUsuario().equals(clave.getText())) {
                if (MenuPrincipal.usuarioActivo == null) {
                    //Ingresa por primera vez
                    new MenuPrincipal(usuarioBD).setVisible(true);
                } else {
                    //Es cambio de usuario
                    MenuPrincipal.usuarioActivo = usuarioBD;
                    RestriccionAcceso.determinarAccesoUsuario(usuarioBD);
                }
                
                this.dispose();
            } else {
                 MensajePresentacion.informarClaveIncorrecta();
            }
        } else {
            MensajePresentacion.informarNombreUsuarioIncorrecto();
        }
    }

    private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
        if (botonSalir.getText().equalsIgnoreCase("Salir")) {
            MenuPrincipal.salirDelSistema();
        } else {
            dispose();
        }
}//GEN-LAST:event_botonSalirActionPerformed

    private void textoDescriptivoVentana1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textoDescriptivoVentana1MouseClicked
        recuperarUsuarioYClave();
    }//GEN-LAST:event_textoDescriptivoVentana1MouseClicked

    private void textoDescriptivoVentana1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textoDescriptivoVentana1MouseEntered
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }//GEN-LAST:event_textoDescriptivoVentana1MouseEntered

    private void textoDescriptivoVentana1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textoDescriptivoVentana1MouseExited
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }//GEN-LAST:event_textoDescriptivoVentana1MouseExited
    
    /**
     * Recupera los datos de ingreso.
     * 
     */
    private void recuperarUsuarioYClave() {
        Properties propiedades = getMailProperties();

        if (propiedades != null) {
            final String correoElectronico =
                    MensajePresentacion.ingresoCadenaDeTexto(
                    "Ingrese el correo electrónico", "", null);

            if (correoElectronico != null) {
                if (PacienteValidacion.validarCorreoElectronico(
                        correoElectronico, true)) {
                    final Usuario usuarioRecuperado =
                            UsuarioLogica.getUsuarioPorCorreoElectronicoEnBd(
                            correoElectronico);

                    if (usuarioRecuperado != null) {

                        if (EMail.sendMail(usuarioRecuperado, correoElectronico,
                                propiedades)) {
                            JOptionPane.showMessageDialog(this,
                                    "El correo electrónico se envió correctamente.\n" +
                                    "Por favor revise su casilla.");
                        } else {
                            MensajePresentacion.informarCorreoElectronicoNoEnviado();
                        }
                    } else {
                        MensajePresentacion.
                                informarCorreoElectronicoNoPerteneceAUsuarioActivo();
                        recuperarUsuarioYClave();
                    }
                } else {
                    MensajePresentacion.errorDatoInvalido();
                    recuperarUsuarioYClave();
                }
            }
        }
    }

    /**
     * Abrir archivo de configuración.
     *
     * @return Las propiedades
     */
    public static Properties getMailProperties() {
        Properties props = new Properties();
        //Se recupera el archivo del directorio donde se ecuentra el jar, se normaliza el espacio
        String fileName = new File(CapaPresentacion.class.
                getProtectionDomain().getCodeSource().getLocation().getPath()).
                getParent().replaceAll("%20", " ");

        InputStream is = null;
        try {
            is = new FileInputStream(CapaLogica.
                    reemplazarUnaBarraInvertidaPorDosBarrasInvertidas(
                    fileName + "\\mail.config"));
            props.load(is);
            return props;
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,
                    "No se puede abrir el archivo de configuración.\n" +
                    "Contácte a personal de Sistemas.",
                    "Información", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
    }

    /**
     * Setea en cada componente del JDialog los eventos que capturarán la tecla
     * enter y escape.
     */
    private void setearEventosQueCapturanTeclaEnterYEscape() {
        //Declaración del evento a capturar
        KeyListener keyListenerEnter = new KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    //Llamada al método que capturará el boton enter y
                    //trabajará sobre el mismo
                    autenticarLogin();
                }
            }
        };
        //Declaración del evento a capturar
        KeyListener keyListenerEscape = new KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    //Llamada al método que capturará el boton enter y
                    //trabajará sobre el mismo
                    dispose();
                }
            }
        };
        //Setear eventos
        usuario.addKeyListener(keyListenerEnter);
        clave.addKeyListener(keyListenerEnter);
        usuario.addKeyListener(keyListenerEscape);
        clave.addKeyListener(keyListenerEscape);

        botonAceptar.addKeyListener(keyListenerEscape);
        botonSalir.addKeyListener(keyListenerEscape);

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonSalir;
    private javax.swing.JPasswordField clave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel panelLogin;
    private javax.swing.JLabel textoClave;
    private javax.swing.JLabel textoDescriptivoVentana;
    private javax.swing.JLabel textoDescriptivoVentana1;
    private javax.swing.JLabel textoUsuario;
    private javax.swing.JTextField usuario;
    // End of variables declaration//GEN-END:variables
}
